#coding:utf-8
require "sinatra"
require "sinatra/sequel"
require "sinatra/namespace"
require "sinatra/param"
require "sinatra/json"
require "sinatra-env"
require "settingslogic"

require "sqlite3"
require "yajl"
require "yajl/json_gem"
require "yaml"


Sequel::Model.plugin(:schema)

[:development, :test].each do |env|
  configure env do
    DB = Sequel.connect(YAML.load_file("config/database.yml")[env.to_s]["database"])
  end
end

require_relative "config/migrations"

register Sinatra::Namespace
helpers Sinatra::Param

set :protection, except: [ :json_csrf ]
set :show_exceptions, false
enable :sessions
set :session_secret, "4EE69F67-6F31-4E00-8DD6-D740D7B42791"

before do
  content_type :json

  headers "Access-Control-Allow-Origin"  => "*",
          "Access-Control-Allow-Methods" => ["OPTIONS", "GET", "POST", "PUT", "DELETE"],
          "Access-Control-Allow-Headers" => "Content-Type"

  begin
    params.merge! JSON.parse(request.env["rack.input"].read)
  rescue
    pass
  end
end

options "/?*" do
  200
end

not_found do
  content_type :json
  status 404

  e = env["sinatra.error"]
  {result: "error", message: e.message}.to_json
end

error do
  content_type :json
  status 500

  e = env["sinatra.error"]
  {result: "error", message: e.message}.to_json
end


set :raise_sinatra_param_exceptions, true

error Sinatra::Param::InvalidParameterError do
  {result: "error", message: "#{env['sinatra.error'].param} 数据不合规"}.to_json
end



["model", "domain", "service"].each do |dir|
  Dir.glob(File.join(dir, "*.rb")).each do |file|
    require_relative file
  end
end


{
  managers: ManagerService,
  paper_types: PaperTypeService,
  paper_requires: PaperRequireService,
  paper_registers: PaperRegisterService,
  organ_registers: OrganRegisterService,
  query: QueryService
}.each do |k,v|
  namespace "/cloap/app/paper_app/#{k}" do
    register v
  end
end
